<template>
  <HeaderTitle title="工人仓存金报告"></HeaderTitle>
  <div class="stockReportPage">
    <div class="row searchBox">
      <div class="row sb-1 items-center">
        <div class="col"><span>存金资料</span></div>
        <div class="col-auto">
          <q-btn
            color="indigo-2"
            class="refreshBtn"
            label="刷新"
            @click="refreshStockInfo()"
          >
            <q-icon name="fa-solid fa-arrows-rotate" class="refreshSVG" />
          </q-btn>
        </div>
      </div>

      <div class="row sb-2 items-center">
        <table class="searchTb">
          <thead>
            <tr>
              <th>部门编号</th>
              <th>金料成色</th>
              <th>金重(克)</th>
              <th></th>
            </tr>
          </thead>
          <tbody v-if="goldTypeInfo.length > 0">
            <tr
              v-for="(gold, index) in goldTypeInfo"
              :key="index"
              :class="{ goldChosen: gold.isChosen }"
            >
              <td>{{ gold.dptcde }}</td>
              <td>{{ gold.stkcde }}</td>
              <td>{{ gold.Quanty }}</td>
              <td
                class="choiceBox"
                @click="toggleChoice(index)"
                :class="{ goldChosen: gold.isChosen }"
              >
                <q-icon
                  name="fa-solid fa-check"
                  color="white"
                  class="checkSVG"
                />
              </td>
            </tr>
          </tbody>
          <tbody v-else>
            <tr>
              <td>{{ "没有数据" }}</td>
              <td>{{ "没有数据" }}</td>
              <td>{{ "没有数据" }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <q-separator color="grey-6" />

      <!-- <div class="row sb-1 items-center">
        <div class="col-auto"><span>存生产单资料</span></div>
        <div class="col-auto">
          <q-btn color="blue-7" class="searchBtn">
            <q-icon name="fa-solid fa-magnifying-glass" class="refreshSVG" />
          </q-btn>
        </div>
      </div> -->
      <div class="row sb-1 items-center">
        <span class="woCnt">生产单总单数: {{ totalOrderNum }}</span>
      </div>
      <div class="row sb-1 items-center">
        <span class="woCnt">生产单总件数: {{ totalOrderQty }}</span>
      </div>
    </div>

    <div v-if="showResult" class="resultBox">
      <div class="row resultTitle items-center">
        <div class="col"><span>生产单，散金明细资料</span></div>
        <div class="col-auto exportBtnBox">
          <q-btn
            color="blue-10"
            class="exportBtn"
            label="导出"
            @click="exportTable()"
          >
            <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
          </q-btn>
        </div>
      </div>

      <q-table
        flat
        bordered
        dense
        separator="cell"
        table-header-class="bg-grey-4"
        :rows="showRows"
        :columns="rtcolumns"
        row-key="NO"
        table-class="resultTb"
        class="resultTb"
        :visible-columns="visCol"
      />
    </div>
  </div>
</template>

<script setup>
import HeaderTitle from "src/components/HeaderTitle.vue";
import { ref, watch } from "vue";
import { useUserStore } from "src/stores/modules/userStore";
import { useReportStore } from "src/stores/modules/reportStore";
import { jsonParseTwice } from "src/utils/utils";
import * as XLSX from 'xlsjs';

const goldTypeInfo = ref([]);
const showResult = ref(false);

const totalOrderNum = ref(0);
const totalOrderQty = ref(0);

const useUser = useUserStore();
const useReport = useReportStore();

let staffCode = null;
let userCode = null;
const reportType = "storage";

const init = async () => {
  // get user data:
  staffCode = useUser.staffID;
  userCode = useUser.currentDept.userCode;
  console.log("getWorkerReportParams", staffCode);
  console.log("getWorkerReportParams", userCode);
};
init();

goldTypeInfo.value = [
  // {
  //   deptCode: "B3T0097",
  //   goldType: "G750",
  //   goldWeight: "58.090",
  //   isChosen: false,
  // },
  // {
  //   deptCode: "B3T0098",
  //   goldType: "G750",
  //   goldWeight: "58.090",
  //   isChosen: false,
  // },
  // {
  //   deptCode: "B3T0099",
  //   goldType: "G750",
  //   goldWeight: "58.090",
  //   isChosen: false,
  // },
];

// Function: Refresh Stock Info
const refreshStockInfo = async () => {
  console.log("refresh...");
  // init
  showResult.value = false;
  const res = await useReport.getWorkerReportResult(
    reportType,
    staffCode,
    userCode,
    "",
    null,
    null
  );
  console.log(res.data);
  rtrows.value = [];
  if (res.data) {
    const test = res.data.data.replace(/\\"/g, '"');
    const json = JSON.parse(test);
    console.log(json);
    goldTypeInfo.value = [
      ...json.data.WorkerLocMstr.map((i) => {
        return {
          ...i,
          isChosen: false,
        };
      }),
    ];
    // console.log(goldTypeInfo.value);
    // goldTypeInfo.value.push({ dptcde: "F3F1274", stkcde: "100", Quanty: 50 });
    rtrows.value = [...rtrows.value, ...json.data.WorderLocDet];
    showRows.value = [...showRows.value, ...json.data.WorderLocDet];
    totalOrderQty.value = json.data.WorkerSum[0].TotalOrdqty;
    totalOrderNum.value = json.data.WorkerSum[0].TotalOrdnum;
  }
};
// refreshStockInfo()
// Result Table
let rtcolumns = [];
let rtrows = ref([]);
let showRows = ref([]);

const visCol = [
  "deptCode",
  "orderNo",
  "goldType",
  "goldWeight",
  "stoneQty",
  "stoneWeight",
];

rtcolumns = [
  {
    name: "NO",
    // required: true,
    label: "#",
    align: "center",
    field: (row) => row.no,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "deptCode",
    align: "center",
    label: "部门编号",
    field: "deptCode",
    sortable: true,
  },
  {
    name: "orderNo",
    align: "center",
    label: "生产单号",
    field: "sonum",
    sortable: true,
  },
  {
    name: "goldType",
    align: "center",
    label: "金料成色",
    field: "stkdesc",
    sortable: false,
  },
  {
    name: "goldWeight",
    align: "center",
    label: "金重(克)",
    field: "quanty",
    sortable: true,
  },
  {
    name: "stoneQty",
    align: "center",
    label: "石粒数(粒)",
    field: "stoneitm",
    sortable: true,
  },
  {
    name: "stoneWeight",
    align: "center",
    label: "石重(ct)",
    field: "stoneqty",
    sortable: true,
  },
];




const toggleChoice = (idx) => {
  let result = [];
  goldTypeInfo.value[idx].isChosen = !goldTypeInfo.value[idx].isChosen;
  const dc = goldTypeInfo.value[idx].dptcde;

  for (let g of goldTypeInfo.value) {
    if (g.isChosen) {
      const arr = rtrows.value
        .filter((i) => {
          return i.stkdesc == g.stkcde;
        })
        .map((item) => {
          return {
            ...item,
            deptCode: dc,
          };
        });
      result = [...result, ...arr];
    }
  }

  showRows.value = result;
//   showRows.value = [
//   {
//     no: 1,
//     deptCode: "C3S0000",
//     orderNo: "散金",
//     goldType: "G750",
//     goldWeight: 0.82,
//     stoneQty: "",
//     stoneWeight: "",
//   },
//   {
//     no: 2,
//     deptCode: "C3S0000",
//     orderNo: "200000480377",
//     goldType: "G750",
//     goldWeight: 0.82,
//     stoneQty: 5,
//     stoneWeight: 0.035,
//   },
// ];
  showResult.value = true;

};

// Function: Download Table as xlxs file
const exportTable = () => {
  console.log("downloading excel file... ");
  const header = rtcolumns.filter(colName=>colName.label!='#').map((colName) => colName.label);
  const rows = showRows.value; // Your data rows here

  const desiredOrder = ['deptCode', 'sonum', 'stkdesc', 'quanty', 'stoneitm','stoneqty'];
  const rearrangedRows = rows.map((row) => {
    const rearrangedRow = {};
    desiredOrder.forEach((property) => {
      rearrangedRow[property] = row[property];
    });
    return rearrangedRow;
  });
  console.log(rearrangedRows)
  console.log(header)

  // Create a new workbook
  const workbook = XLSX.utils.book_new();
    // Create a worksheet
  // const worksheet = XLSX.utils.json_to_sheet(showRows.value);
  const worksheet = XLSX.utils.json_to_sheet(rearrangedRows);
  XLSX.utils.sheet_add_aoa(worksheet, [header], { origin: "A1" });

  // Add the worksheet to the workbook
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  const wbout = XLSX.write(workbook, {
    bookType: 'csv',
    type: 'array',
    bookSST: false,
    defaultEncoding: 'UTF-16LE'
  });

  // Generate the CSV file
  const blob = new Blob([wbout], { type: 'application/octet-stream' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '工人仓存金报告.csv';
  link.click();
  URL.revokeObjectURL(link.href);

};
</script>

<style lang="scss">
.stockReportPage {
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }

  .searchBox {
    width: 100%;
    padding: 10px 15px 10px 15px;
    margin-top: 10px;
    background-color: rgba(255, 255, 255, 0.863);
    border-radius: 10px;

    .sb-1 {
      width: 100%;
      margin-bottom: 10px;
      font-weight: bold;
      .refreshBtn {
        color: #4436d0 !important;
        font-size: 1rem;
        font-weight: bold;
        .refreshSVG {
          margin-left: 10px;
          @media (max-width: 480px) {
            font-size: 1.3rem;
          }
        }
      }
      .searchBtn {
        margin-left: 10px;
        font-size: 0.8rem;
        border-radius: 10px;
        @media (max-width: 480px) {
          font-size: 0.6rem;
        }
      }
      .woCnt {
        font-weight: bold;
        color: #4436d0;
        font-size: 1rem;
      }
    }
    .sb-2 {
      width: 100%;
      margin-bottom: 10px;
      .searchTb {
        width: 100%;
        font-size: 1.2rem;
        @media (max-width: 480px) {
          font-size: 1rem;
        }
        thead {
          background-color: #c2d3ff;
        }
        tbody {
          text-align: center;
          background-color: white;
        }
        .choiceBox {
          background-color: #d8dff4;
          .checkSVG {
            font-size: 2rem;
            @media (max-width: 480px) {
              font-size: 1.3rem;
            }
          }
        }
        .goldChosen {
          background-color: #acbadf !important;
        }
      }
    }
  }

  .resultBox {
    width: 100%;
    margin-top: 10px;
    .resultTitle {
      font-weight: bold;
      color: white;
      margin-bottom: 10px;
    }
    .exportBtnBox {
      margin-left: 10px;
      text-align: right;
      .exportBtn {
        font-size: 1rem;
        .exportSVG {
          margin-left: 5px;
        }
      }
    }
    .resultTb >>> .q-table th {
      width: 100%;
      border: 1px solid #d9d9d9;
    }
    .resultTbStyle {
      font-weight: bold;
    }
  }
}
</style>
